Sep 1, 2023
settings.py file, you need to configure settings related to media files.os.MEDIA_URL: The URL prefix for serving media files.MEDIA_ROOT: The absolute filesystem path to the directory where media files will be stored.-To handle user uploads, you typically use a model field like models.ImageField or models.FileField. For example, if you have a model named Profile with a field for the user’s profile picture:
from django.db import models
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
profile_picture = models.ImageField(upload_to='profile_pics/')upload_to parameter specifies the subdirectory within the MEDIA_ROOT where the uploaded files will be stored.urls.py file:from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
# Your other URL patterns here...
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)if settings.DEBUG block ensures that this configuration is applied only when running in development mode.MEDIA_ROOT directory, using the same MEDIA_URL prefix.In your project’s settings.py, add the following configurations for media files:
image_upload_demo/models.py):Run migrations to create the database tables for the model:
image_upload_demo/forms.py):image_upload_demo/views.py):from django.shortcuts import render
from .forms import ImageUploadForm
def upload_image(request):
if request.method == 'POST':
form = ImageUploadForm(request.POST, request.FILES)
if form.is_valid():
form.save()
# Redirect or render a success message
else:
form = ImageUploadForm()
return render(request, 'image_upload_demo/upload.html', {'form': form})image_upload_demo/templates/image_upload_demo/upload.html):image_upload_demo/urls.py):image_upload_project/urls.py):During development, you can serve media files by adding the following code to your project’s urls.py:
from django.conf import settings
from django.conf.urls.static import static
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)For production, you’ll need to configure your web server (like Nginx or Apache) to serve media files.
Run the development server to test your image upload:
Open your browser and navigate to http://127.0.0.1:8000/image_upload_demo/upload/.
You should see a form to upload images.
Once you upload images using the form, they will be saved in the media/uploads/ directory within your project.
This demonstrates the use of image upload functionality in a Django project.
Remember that in a production environment, you’ll need to configure your web server to serve media files.
Manish Patel